using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.Autoscaling;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using System.Diagnostics;

namespace FtpWebRole
{
    public class WebRole : RoleEntryPoint
    {
        private Autoscaler scaler;

        public override bool OnStart()
        {
            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            // start the diagnostic monitor
            var config = DiagnosticMonitor.GetDefaultInitialConfiguration();
            var cloudStorageAccount =
                CloudStorageAccount.Parse(
                  RoleEnvironment.GetConfigurationSettingValue(
                  "Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString"));

            config.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1);
            config.Logs.ScheduledTransferLogLevelFilter = LogLevel.Verbose; 
            DiagnosticMonitor.Start(cloudStorageAccount, config);

            // log immediately
            var container = cloudStorageAccount.CreateCloudBlobClient().GetContainerReference("autoscaling");
            container.CreateIfNotExist();

            // start the scaler
            try
            {
                // make sure WaIISHost.exe.config is created and set to be "copy always"
                // for details, please see:
                // http://blogs.msdn.com/b/windowsazure/archive/2010/12/02/new-full-iis-capabilities-differences-from-hosted-web-core.aspx
                scaler = EnterpriseLibraryContainer.Current.GetInstance<Autoscaler>();
                scaler.Start();

                container.GetBlobReference("log.txt").UploadText("Start scaler successfully!");
                Trace.WriteLine("Scaler started...", "Verbose");
            }
            catch (Exception e)
            {
                container.GetBlobReference("log.txt")
                    .UploadText(string.Format("{0}\n{1}", e.Message, e.StackTrace));
            }
            
            return base.OnStart();
        }

        public override void OnStop()
        {
            scaler.Stop();
            base.OnStop();
        }
    }
}
